package com.hnluchuan.bmjlearning.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hnluchuan.bmjlearning.dto.UserDTO;
import com.hnluchuan.bmjlearning.service.*;
import com.hnluchuan.bmjlearning.util.SpringSecurityUtils;
import com.hnluchuan.core.support.TokenInterceptor;
import com.hnluchuan.utils.common.DateUtils;
import com.hnluchuan.utils.common.DevUtils;
import com.hnluchuan.utils.common.MyWebUtils;
import com.hnluchuan.utils.exception.KException;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.orm.hibernate5.HibernateOptimisticLockingFailureException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Calendar;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class BaseAdminController extends CoreBaseController{
	@Autowired
	protected DesService desService;
	@Autowired
	protected CoreService coreService;
	@Value("${default.password}")
	protected String defaultPassword;
	@Value("${default.salt}")
	protected String defaultSalt;
	@Autowired
	protected CustomerServicePackageService customerServicePackageService;

	@Autowired
	protected AgentServicePackageService agentServicePackageService;

	@Autowired
	protected RoleService roleService;

	@Autowired
	protected ServicePackageService servicePackageService;

	@Autowired
	protected CustomerService customerService;

	@Autowired
	protected AgentService agentService;

	@Autowired
	protected StudentService studentService;

	protected static Logger logger = Logger.getLogger(BaseController.class);

	@Autowired
	protected MenuService menuService;
	@Autowired
	protected AuthorityService authorityService;
	@Autowired
	protected UserRoleService userRoleService;
	@Autowired
	protected RoleMenuService roleMenuService;

	@Autowired
	protected BizConfigService bizConfigService;

	@Autowired
	protected CityService cityService;

	@Autowired
	protected ProvinceService provinceService;

	@Autowired
	protected DistrictService districtService;


	@Autowired
	protected UserService userService;

	protected UserDTO getUserFromSession() {
		if (DevUtils.isLocal()) {
			return userService.load(13L);
		}
		UserDTO user = null;
		Long userIdFromSession = (Long) MyWebUtils.getCurrentRequest().getSession().getAttribute("wx.userId");
		if (userIdFromSession != null) {
			user = userService.load(userIdFromSession);
		}
		return user;
	}

	protected void setUserToSession(UserDTO user) {
		if (user != null) {
			MyWebUtils.getCurrentRequest().getSession().setAttribute("wx.userId", user.getId());
		}
	}

	protected String getRequestUrlWithQueryString() {
		String url = MyWebUtils.getCurrentRequest().getRequestURL().toString();
		String q = MyWebUtils.getCurrentRequest().getQueryString();
		if (StringUtils.isNotBlank(q)) {
			url += "?" + q;
		}
		return url;
	}

	@ResponseBody
	public String okJson() {
		JSONObject json = new JSONObject();
		json.put("success", true);
		return json.toJSONString();
	}

	protected UserDTO getCurrentUserDTO() {
		if (SpringSecurityUtils.getCurrentUser() != null) {
			return userService.load(SpringSecurityUtils.getCurrentUser().getId());
		} else {
			Long userId = (Long) MyWebUtils.getCurrentRequest().getAttribute("currentUserId");
			if (userId != null) {
				return userService.load(userId);
			} else {
				return null;
			}
		}
	}

	protected String successPage(String msg) {
		if (StringUtils.isBlank(msg)) {
			msg = "操作成功";
		}
		MyWebUtils.getCurrentRequest().setAttribute("msg", msg);
		return "common/success";
	}

	protected String failPage(Exception e) {
		String msg = e.getMessage();
		if (StringUtils.isBlank(msg)) {
			msg = "系统错误";
		}
		MyWebUtils.getCurrentRequest().setAttribute("msg", msg);
		MyWebUtils.getCurrentRequest().setAttribute("stacks", e.getStackTrace());
		return "common/fail";
	}

	protected String failPage(String msg) {
		if (StringUtils.isBlank(msg)) {
			msg = "操作成功";
		}
		MyWebUtils.getCurrentRequest().setAttribute("msg", msg);
		return "common/fail";
	}
	protected boolean isAjaxRequest() {
		String requestType = MyWebUtils.getCurrentRequest().getHeader("X-Requested-With");
		return StringUtils.isNotBlank(requestType);
	}

	public Date addDays(Date date, Integer days){
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.DATE, days);

		return c.getTime();
	}

	public Long getDateDiff(Date startDate, Date endDate, TimeUnit timeUnit){
		Date startOfStartDate = DateUtils.getBeginningOfADay(startDate);
		Date endOfEndDate = DateUtils.getEndOfADay(endDate);
		Long diffInMillies = endOfEndDate.getTime() - startOfStartDate.getTime();
		return timeUnit.convert(diffInMillies, TimeUnit.MILLISECONDS);
	}

    @ExceptionHandler
    public String onException(Exception e, HttpServletRequest request, HttpServletResponse response) throws Exception {
    	logger.error(e.getMessage(), e);
    	if (isAjaxRequest()) {
    		JSONObject json = new JSONObject();
        	json.put("success", false);
        	json.put("msg", e.getMessage());
        	json.put("statusCode", 300);
    		json.put("message", e.getMessage());
    		response.setContentType("application/json; charset=UTF-8");
    		response.getWriter().print(json.toJSONString());
    		return null;
    	} else {
    		return failPage(e);
    	}
    	
    }
}
